package kitwee.com.kanpad;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.umeng.analytics.MobclickAgent;
import com.uuzuche.lib_zxing.activity.CodeUtils;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.apache.commons.codec.binary.Hex;
import org.apache.commons.codec.digest.DigestUtils;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import kitwee.com.kanpad.bean.LoginBean;
import kitwee.com.kanpad.bean.QRCodeLogin;
import kitwee.com.kanpad.common.KanpadStrings;
//import kitwee.com.kanpad.service.PushService;
import kitwee.com.kanpad.orderDetail.SerialPortActivity;
import kitwee.com.kanpad.orderDetail.SerialPortPreferences;
import okhttp3.Call;
import okhttp3.OkHttpClient;
import utils.DeviceUtils;
import utils.FlavorHelper;
import utils.SPUtils;

@SuppressLint("NewApi")
public class LoginActivity extends BaseActivity {
    View main;
    String userName;
    String pwd;
    ProgressDialog progressDialog;
    @BindView(R.id.email_sign_in_button)
    Button emailSignInButton;
    @BindView(R.id.iv_login_what)
    ImageView ivLoginWhat;
    @BindView(R.id.ll_login_scan)
    LinearLayout ll_login_scan;
    @BindView(R.id.ll_login_input)
    LinearLayout ll_login_input;
    @BindView(R.id.username)
    EditText userText;
    @BindView(R.id.password)
    EditText pwdText;
    @BindView(R.id.deviceID)
    TextView deviceID;
    @BindView(R.id.iv_qr_code)
    ImageView ivQrCode;
    private Boolean loginSUCCESS;
    @BindView(R.id.imageView)
    ImageView imageIcon;
    private String endPoint;


    @SuppressLint("InflateParams")
    @Override
    public void onCreate(Bundle savedInstanceState) {
        MyMultiDexApplication.getInstance().addActivity(this);
        super.onCreate(savedInstanceState);
        //PushService.restart();
        getLayoutInflater();
        main = LayoutInflater.from(this).inflate(R.layout.activity_login, null);
        hideBottomUIMenu();
        progressDialog = new ProgressDialog(LoginActivity.this);
        progressDialog.setMessage("登陆中...");
        progressDialog.setCancelable(true);
        setContentView(main);
        ButterKnife.bind(this);
        userName = SPUtils.getString(this, "user");
        pwd = SPUtils.getString(this, "pwd");
        loginSUCCESS = SPUtils.getBoolean(this, "login");
        //设置设备ID
        String yunPaiId = DeviceUtils.getPadionId();
        deviceID.setText(yunPaiId);
        createQrcode(deviceID);
        EventBus.getDefault().register(this);
        if ((!"".equals(userName)) && (!"".equals(pwd))) {
            checkUser();
        } else if (loginSUCCESS) {
            Intent intent = new Intent();
            String textID = deviceID.getText().toString();
            intent.putExtra("PADID", textID);
            intent.setClass(LoginActivity.this, MainActivity.class);
            startActivity(intent);
            LoginActivity.this.finish();
        } else { // 第一次使用
            checkSerialPortConfigs();
        }

    }

    private void checkSerialPortConfigs() {

        if (Build.MANUFACTURER.equals("Netease")) {
            return;
        }
        if (SerialPortPreferences.getSerialPortParam() == null) {
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setMessage("尚未配置串口参数，是否前往配置页面？");
            builder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    SerialPortActivity.start(LoginActivity.this);
                }
            }).setNegativeButton(android.R.string.cancel, null).show();
        }
    }

    private boolean ISSCAN = true;

    @OnClick({R.id.email_sign_in_button, R.id.iv_login_what})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.email_sign_in_button:
                userName = userText.getText().toString();
                pwd = pwdText.getText().toString();

                if ((!"".equals(userName)) && (!"".equals(pwd))) {
                    checkUser();
                }

                break;
            case R.id.iv_login_what:
                //切换登陆方式
                if (ISSCAN) {
                    ll_login_scan.setVisibility(View.GONE);
                    ll_login_input.setVisibility(View.VISIBLE);
                    ISSCAN = false;
                } else {
                    ll_login_scan.setVisibility(View.VISIBLE);
                    ll_login_input.setVisibility(View.GONE);
                    ISSCAN = true;
                }
                break;
        }
    }


    public static void start(Context context, boolean force) {
        start(context, force, false);
    }

    public static void start(Context context, boolean force, boolean newTask) {
        Intent intent = new Intent(context, LoginActivity.class);
        if (newTask) {
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); // App context
        }
        context.startActivity(intent);
    }


    private void createQrcode(TextView deviceID) {
        String ids = deviceID.getText().toString();
        Bitmap image = CodeUtils.createImage("yunpai&" + ids, 400, 400, null);
        ivQrCode.setImageBitmap(image);
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Override
    protected void onStop() {
        // TODO Auto-generated method stub
        super.onStop();

        if (progressDialog != null) {
            progressDialog.dismiss();
        }
    }

    /**
     * 隐藏虚拟按键，并且全屏
     */
    protected void hideBottomUIMenu() {
        //隐藏虚拟按键，并且全屏
        if (Build.VERSION.SDK_INT > 11 && Build.VERSION.SDK_INT < 19) { // lower api
            View v = this.getWindow().getDecorView();
            v.setSystemUiVisibility(View.GONE);
        } else if (Build.VERSION.SDK_INT >= 19) {
            //for new api versions.
            View decorView = getWindow().getDecorView();
            int uiOptions = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY | View.SYSTEM_UI_FLAG_FULLSCREEN;
            decorView.setSystemUiVisibility(uiOptions);
        }
    }

    /**
     * 验证账户名密码.登陆
     */
    private void checkUser() {
        if (main != null) {
            progressDialog.show();
            final long time = System.currentTimeMillis();
            String yunPaiId = DeviceUtils.getPadionId();
            LogUtils.e("yunPaiId : " + yunPaiId);
            final String digest = new String(Hex.encodeHex(DigestUtils.md5(
                    ("aHR0cHM6Ly93d3cua2l0d2VlLmNvbS8=" + "guest" + time).getBytes())));
            endPoint = BuildConfig.API_ENDPOINT;
            OkHttpUtils.get()
                    .url(endPoint + "/login?t=" + time)
                    .addParams("phone", userName)
                    .addParams("kanban_no", yunPaiId)
                    .addParams("pwd", pwd)
                    .addParams("pd", digest)
                    .build()
                    .execute(new StringCallback() {
                        @Override
                        public void onError(Call call, Exception e, int id) {
                            e.printStackTrace();
                            progressDialog.dismiss();
                            LogUtils.e("登陆失败 : " + e.getMessage());
                        }

                        @Override
                        public void onResponse(String response, int id) {
                            progressDialog.dismiss();
                            System.out.println(response);
                            LoginBean loginBean = JSONObject.parseObject(response, LoginBean.class);
                            if (TextUtils.equals("200", loginBean.getStatusCode())) {
                                LoginSerial();

                                String data = loginBean.getData();
                                SPUtils.putString(LoginActivity.this, "key", data);
                                SPUtils.putString(LoginActivity.this, "user", userName);
                                SPUtils.putString(LoginActivity.this, "pwd", pwd);
                                SPUtils.putString(LoginActivity.this, "KANBANID", deviceID.getText().toString());
                                LogUtils.e("deviceno:" + deviceID.getText().toString());

                                Intent intent = new Intent();
                                String textID = deviceID.getText().toString();
                                intent.putExtra("PADID", textID);
                                intent.setClass(LoginActivity.this, MainActivity.class);
                                startActivity(intent);
                                LoginActivity.this.finish();

                            } else if (TextUtils.equals("300", loginBean.getStatusCode())) {
                                ToastUtils.showShort("请检查用户名或密码是否正确");
                            }
                        }
                    });
        }
    }

    /**
     * 登陆采集.
     */
    private void LoginSerial() {
        String ACCESS_KEY_ID = "kitwee";
        String ACCESS_KEY_SECRET = "aHR0cHM6Ly93d3cua2l0d2VlLmNvbS8=";
        String GUEST_KEY = "aHR0cHM6Ly93d3cua2l0d2VlLmNvbS8=";
        final long time = System.currentTimeMillis();
        final String digest = new String(Hex.encodeHex(DigestUtils.md5(
                (GUEST_KEY + "guest" + time).getBytes())));

        OkHttpUtils.post()
                .url(BuildConfig.API_SERIAL_LOGIN_URL + "/login?t=" + time)
                .addParams("accessKeyID", ACCESS_KEY_ID)
                .addParams("accessKeySecret", ACCESS_KEY_SECRET)
                .addParams("pd", digest)
                .build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                LogUtils.e(e.getMessage());
                //如果失败重新登陆
                LoginSerial();
            }

            @Override
            public void onResponse(String response, int id) {
                LogUtils.e(response);
                LoginBean loginBean = JSONObject.parseObject(response, LoginBean.class);
                String data = loginBean.getData();
                SPUtils.putString(getApplicationContext(), "SerialPortKey", data);
            }
        });
    }

    @Subscribe
    public void getMesageEvent(QRCodeLogin qrCodeLogin) {
        if (qrCodeLogin != null) {
            LogUtils.e("qrcode event back log : " + qrCodeLogin.getKey());
            LogUtils.e("qrcode event back log : " + qrCodeLogin.getName());
            LogUtils.e("qrcode event back log : " + qrCodeLogin.getQRLOGIN());
            // 重新建立Socket连接
            //PushService.restart();
            SPUtils.putString(LoginActivity.this, "key", qrCodeLogin.getKey());
            SPUtils.putString(LoginActivity.this, "user", qrCodeLogin.getName());
            SPUtils.putBoolean(LoginActivity.this, "login", true);

//        SPUtils.putString(LoginActivity.this, "pwd", pwd);
            SPUtils.putString(LoginActivity.this, "KANBANID", deviceID.getText().toString());
            Intent intent = new Intent();
            String textID = deviceID.getText().toString();
            intent.putExtra("PADID", textID);
            intent.setClass(LoginActivity.this, MainActivity.class);
            startActivity(intent);
            LoginActivity.this.finish();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }
}